<template>
  <div class="assignments-container">
    <div class="page-header">
      <h2>句子分配管理</h2>
      <p>为用户分配录音句子，控制录音任务的分发</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ statistics.total_users || 0 }}</div>
              <div class="stat-label">总用户数</div>
            </div>
            <i class="el-icon-user stat-icon"></i>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ statistics.users_with_assignments || 0 }}</div>
              <div class="stat-label">已分配用户</div>
            </div>
            <i class="el-icon-s-order stat-icon"></i>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ statistics.total_assignments || 0 }}</div>
              <div class="stat-label">总分配数</div>
            </div>
            <i class="el-icon-document stat-icon"></i>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ statistics.total_completed || 0 }}</div>
              <div class="stat-label">已完成录音</div>
            </div>
            <i class="el-icon-check stat-icon"></i>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="showBatchAssignDialog = true">
        <i class="el-icon-plus"></i>
        批量分配
      </el-button>
      <el-button @click="refreshData">
        <i class="el-icon-refresh"></i>
        刷新数据
      </el-button>
    </div>

    <!-- 用户分配列表 -->
    <el-card class="table-card">
      <div slot="header" class="card-header">
        <span>用户分配情况</span>
      </div>
      
      <el-table 
        :data="users" 
        v-loading="loading"
        style="width: 100%"
        @row-click="viewUserDetail"
      >
        <el-table-column prop="user_id" label="用户ID" width="80"></el-table-column>
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column label="分配情况" width="200">
          <template slot-scope="scope">
            <div class="assignment-info">
              <span class="total">总数: {{ scope.row.total_assigned || 0 }}</span>
              <span class="completed">已完成: {{ scope.row.completed || 0 }}</span>
              <span class="pending">待录制: {{ scope.row.pending || 0 }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="完成率" width="120">
          <template slot-scope="scope">
            <el-progress 
              :percentage="scope.row.completion_rate || 0" 
              :color="getProgressColor(scope.row.completion_rate)"
              :stroke-width="8"
            ></el-progress>
          </template>
        </el-table-column>
        <el-table-column prop="last_activity" label="最后活动" width="160">
          <template slot-scope="scope">
            {{ formatTime(scope.row.last_activity) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" @click.stop="assignToUser(scope.row)">分配句子</el-button>
            <el-button size="mini" type="info" @click.stop="viewUserDetail(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 批量分配对话框 -->
    <el-dialog title="批量分配句子" :visible.sync="showBatchAssignDialog" width="600px">
      <el-form :model="batchForm" label-width="100px">
        <el-form-item label="选择用户">
          <el-select 
            v-model="batchForm.userIds" 
            multiple 
            placeholder="请选择用户"
            style="width: 100%"
          >
            <el-option 
              v-for="user in allUsers" 
              :key="user.id" 
              :label="user.username" 
              :value="user.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分配方式">
          <el-radio-group v-model="batchForm.assignmentType">
            <el-radio label="random">随机分配</el-radio>
            <el-radio label="fixed">指定句子</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分配数量" v-if="batchForm.assignmentType === 'random'">
          <el-input-number v-model="batchForm.count" :min="1" :max="50"></el-input-number>
        </el-form-item>
        <el-form-item label="选择句子" v-if="batchForm.assignmentType === 'fixed'">
          <el-select 
            v-model="batchForm.sentenceIds" 
            multiple 
            placeholder="请选择句子"
            style="width: 100%"
          >
            <el-option 
              v-for="sentence in allSentences" 
              :key="sentence.id" 
              :label="sentence.content" 
              :value="sentence.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="showBatchAssignDialog = false">取消</el-button>
        <el-button type="primary" @click="handleBatchAssign" :loading="batchAssigning">确定分配</el-button>
      </div>
    </el-dialog>

    <!-- 单用户分配对话框 -->
    <el-dialog title="分配句子" :visible.sync="showAssignDialog" width="600px">
      <div v-if="currentUser">
        <h4>用户: {{ currentUser.username }}</h4>
        <el-tabs v-model="assignTab">
          <el-tab-pane label="随机分配" name="random">
            <el-form :model="assignForm" label-width="100px">
              <el-form-item label="分配数量">
                <el-input-number v-model="assignForm.count" :min="1" :max="50"></el-input-number>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleRandomAssign" :loading="assigning">随机分配</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="指定句子" name="fixed">
            <el-form :model="assignForm" label-width="100px">
              <el-form-item label="选择句子">
                <el-select 
                  v-model="assignForm.sentenceIds" 
                  multiple 
                  placeholder="请选择句子"
                  style="width: 100%"
                >
                  <el-option 
                    v-for="sentence in allSentences" 
                    :key="sentence.id" 
                    :label="sentence.content" 
                    :value="sentence.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleFixedAssign" :loading="assigning">确定分配</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog title="用户分配详情" :visible.sync="showDetailDialog" width="800px">
      <div v-if="userDetail">
        <div class="detail-header">
          <h4>{{ userDetail.user_info.username }} 的分配详情</h4>
          <div class="detail-stats">
            <span>总数: {{ userDetail.assignments.length }}</span>
            <span>已完成: {{ userDetail.progress.completed }}</span>
            <span>待录制: {{ userDetail.progress.pending }}</span>
            <span>完成率: {{ userDetail.progress.completion_rate.toFixed(1) }}%</span>
          </div>
        </div>
        <el-table :data="userDetail.assignments" style="width: 100%">
          <el-table-column prop="sequence_order" label="顺序" width="60"></el-table-column>
          <el-table-column prop="content" label="句子内容" min-width="300"></el-table-column>
          <el-table-column label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.is_completed ? 'success' : 'info'">
                {{ scope.row.is_completed ? '已完成' : '待录制' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="recorded_at" label="录制时间" width="160">
            <template slot-scope="scope">
              {{ formatTime(scope.row.recorded_at) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="detail-actions">
          <el-button @click="clearUserAssignments(userDetail.user_info.user_id)" type="danger">清空分配</el-button>
          <el-button @click="assignToUser(userDetail.user_info)" type="primary">重新分配</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Assignments',
  data() {
    return {
      loading: false,
      users: [],
      statistics: {},
      allUsers: [],
      allSentences: [],
      
      // 批量分配
      showBatchAssignDialog: false,
      batchAssigning: false,
      batchForm: {
        userIds: [],
        assignmentType: 'random',
        count: 5,
        sentenceIds: []
      },
      
      // 单用户分配
      showAssignDialog: false,
      assigning: false,
      currentUser: null,
      assignTab: 'random',
      assignForm: {
        count: 5,
        sentenceIds: []
      },
      
      // 用户详情
      showDetailDialog: false,
      userDetail: null
    }
  },
  
  async created() {
    await this.loadData()
  },
  
  methods: {
    async loadData() {
      this.loading = true
      try {
        // 加载分配概览
        try {
          const overview = await this.$store.dispatch('fetchAssignmentOverview')
          this.users = overview.users || []
          this.statistics = overview.statistics || {}
        } catch (overviewError) {
          console.error('分配概览加载失败:', overviewError)
          this.$errorMessage('分配概览加载失败，使用默认数据')
          // 使用默认数据
          this.users = []
          this.statistics = {
            total_users: 0,
            users_with_assignments: 0,
            total_assignments: 0,
            total_completed: 0
          }
        }

        // 加载所有用户和句子（用于分配选择）
        await this.loadAllUsers()
        await this.loadAllSentences()

        // 如果概览数据为空，但有用户数据，创建基础显示数据
        if (this.users.length === 0 && this.allUsers.length > 0) {
          this.users = this.allUsers.map(user => ({
            user_id: user.id,
            username: user.username,
            total_assigned: 0,
            completed: 0,
            pending: 0,
            completion_rate: 0,
            last_activity: null
          }))
          this.statistics.total_users = this.allUsers.length
        }
      } catch (error) {
        this.$errorMessage('加载数据失败')
      } finally {
        this.loading = false
      }
    },
    
    async loadAllUsers() {
      try {
        const response = await this.$store.dispatch('fetchUsers', { page: 1, size: 1000 })
        this.allUsers = response.users || []
      } catch (error) {
        console.error('加载用户列表失败:', error)
      }
    },
    
    async loadAllSentences() {
      try {
        const response = await this.$store.dispatch('fetchSentences', { page: 1, size: 1000 })
        this.allSentences = response.sentences || []
      } catch (error) {
        console.error('加载句子列表失败:', error)
      }
    },
    
    async refreshData() {
      await this.loadData()
      this.$successMessage('数据已刷新')
    },
    
    // 分配句子给单个用户
    assignToUser(user) {
      this.currentUser = user
      this.assignForm = {
        count: 5,
        sentenceIds: []
      }
      this.assignTab = 'random'
      this.showAssignDialog = true
    },
    
    // 随机分配
    async handleRandomAssign() {
      if (!this.currentUser || !this.assignForm.count) {
        this.$errorMessage('请填写完整信息')
        return
      }
      
      this.assigning = true
      try {
        await this.$store.dispatch('assignRandomSentences', {
          userId: this.currentUser.user_id,
          count: this.assignForm.count
        })
        this.$successMessage('随机分配成功')
        this.showAssignDialog = false
        await this.refreshData()
      } catch (error) {
        this.$errorMessage('分配失败')
      } finally {
        this.assigning = false
      }
    },
    
    // 指定句子分配
    async handleFixedAssign() {
      if (!this.currentUser || !this.assignForm.sentenceIds.length) {
        this.$errorMessage('请选择要分配的句子')
        return
      }
      
      this.assigning = true
      try {
        await this.$store.dispatch('assignSentences', {
          userId: this.currentUser.user_id,
          sentenceIds: this.assignForm.sentenceIds,
          replaceExisting: true
        })
        this.$successMessage('分配成功')
        this.showAssignDialog = false
        await this.refreshData()
      } catch (error) {
        this.$errorMessage('分配失败')
      } finally {
        this.assigning = false
      }
    },
    
    // 批量分配
    async handleBatchAssign() {
      if (!this.batchForm.userIds.length) {
        this.$errorMessage('请选择用户')
        return
      }
      
      if (this.batchForm.assignmentType === 'fixed' && !this.batchForm.sentenceIds.length) {
        this.$errorMessage('请选择要分配的句子')
        return
      }
      
      this.batchAssigning = true
      try {
        await this.$store.dispatch('batchAssignSentences', {
          userIds: this.batchForm.userIds,
          assignmentType: this.batchForm.assignmentType,
          count: this.batchForm.count,
          sentenceIds: this.batchForm.sentenceIds
        })
        this.$successMessage('批量分配成功')
        this.showBatchAssignDialog = false
        await this.refreshData()
      } catch (error) {
        this.$errorMessage('批量分配失败')
      } finally {
        this.batchAssigning = false
      }
    },
    
    // 查看用户详情
    async viewUserDetail(user) {
      try {
        this.userDetail = await this.$store.dispatch('fetchUserAssignments', user.user_id)
        this.showDetailDialog = true
      } catch (error) {
        this.$errorMessage('加载用户详情失败')
      }
    },
    
    // 清空用户分配
    async clearUserAssignments(userId) {
      try {
        await this.$confirm('确定要清空该用户的所有分配吗？', '确认操作', {
          type: 'warning'
        })
        
        await this.$store.dispatch('clearUserAssignments', userId)
        this.$successMessage('清空成功')
        this.showDetailDialog = false
        await this.refreshData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$errorMessage('清空失败')
        }
      }
    },
    
    // 工具方法
    getProgressColor(percentage) {
      if (percentage >= 80) return '#67c23a'
      if (percentage >= 50) return '#e6a23c'
      return '#f56c6c'
    },
    
    formatTime(time) {
      if (!time) return '-'
      return new Date(time).toLocaleString()
    }
  }
}
</script>

<style scoped>
.assignments-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: var(--text-primary);
}

.page-header p {
  margin: 0;
  color: var(--text-secondary);
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  position: relative;
  overflow: hidden;
}

.stat-content {
  position: relative;
  z-index: 2;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: var(--primary);
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: var(--text-secondary);
}

.stat-icon {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 40px;
  color: var(--primary-light);
  opacity: 0.3;
}

.toolbar {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.assignment-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.assignment-info span {
  font-size: 12px;
}

.total { color: var(--text-primary); }
.completed { color: #67c23a; }
.pending { color: #e6a23c; }

.detail-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--border-color);
}

.detail-stats {
  margin-top: 10px;
  display: flex;
  gap: 20px;
}

.detail-stats span {
  font-size: 14px;
  color: var(--text-secondary);
}

.detail-actions {
  margin-top: 20px;
  text-align: right;
}
</style>
